﻿using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class OpenStyleCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly IInteractionManager interaction;

		public OpenStyleCommand(MasterPresenter presenter, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = (this.presenter.CurrentDocument != null);
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			var style = this.GetStyle();
			if (style == null) return;

			var filename = style.FullPath;
			if (!this.interaction.AskForStyleFile(ref filename)) return;

			style.Open(filename);
			this.presenter.CurrentDocument = style;
		}

		private StylePresenter GetStyle()
		{
			var document = this.presenter.CurrentDocument;
			if (document is DocumentPresenter)
			{
				return ((DocumentPresenter)document).Style;
			}
			if (document is SchemaPresenter)
			{
				return ((SchemaPresenter)document).Document.Style;
			}
			if (document is StylePresenter)
			{
				return ((StylePresenter)document);
			}
			return null;
		}
	}
}
